package com.boodaba.todocarts.app;

import com.boodaba.todocarts.domain.ILabelRepository;
import com.boodaba.todocarts.domain.Label;
import com.google.inject.Inject;

public class LabelEditPresenter extends BasePresenter<ILabelEditActivity> {

	private ILabelRepository mLabelRepository;
	private Label mTargetLabel;
	
	@Inject
	public LabelEditPresenter(ILabelRepository labelRepository) {
		mLabelRepository = labelRepository;
	}

	@Override
	public void initializeWith(ILabelEditActivity labelEditActivity) {
		super.initializeWith(labelEditActivity);
		
		String labelTitle = getActivity().getTargetTitle();
		
		if (labelTitle == null) {
			getActivity().setNew();
			return;
		}
		
		mTargetLabel = mLabelRepository.getLabelByTitle(labelTitle);
		getActivity().setEdit(mTargetLabel.getTitle());
	}

	public void save() {
		String input = getActivity().getInputString().trim();
		if (input.length() == 0
			|| mLabelRepository.getLabelByTitle(input) != null) {
			getActivity().exit();
			return;
		}
		
		if (mTargetLabel != null) {
			mTargetLabel.setTitle(input);
		}
		if (mTargetLabel == null) {
			mTargetLabel = new Label(input);
		}
		
		mLabelRepository.save(mTargetLabel);
		getActivity().exit();
	}

	public void delete() {
		if (mTargetLabel != null) {
			mLabelRepository.delete(mTargetLabel);
		}
		getActivity().exit();
	}
}
